package com.yf.stat.modules.total.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.api.controller.BaseController;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.base.utils.DateUtils;
import com.yf.stat.modules.total.dto.StatTotalLearnDTO;
import com.yf.stat.modules.total.dto.request.StatTotalLearnReqDTO;
import com.yf.stat.modules.total.service.StatTotalLearnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.List;

/**
* <p>
* 学习统计控制器
* </p>
*
* @author 聪明笨狗
* @since 2021-06-04 10:13
*/
@Api(tags={"学习统计"})
@RestController
@RequestMapping("/api/stat/total/learn")
public class StatTotalLearnController extends BaseController {

    @Autowired
    private StatTotalLearnService baseService;


    /**
     * 分页查找
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @PostMapping("/paging")
    public ApiRest<IPage<StatTotalLearnDTO>> paging(@RequestBody PagingReqDTO<StatTotalLearnReqDTO> reqDTO) {

        StatTotalLearnReqDTO params = reqDTO.getParams();

        if(params==null){
            params = new StatTotalLearnReqDTO();
        }


        if(StringUtils.isBlank(params.getStartDate())
                || StringUtils.isBlank(params.getEndDate())){
            this.fillDateQuery(params, -30);
        }


        params.setOrderType("DESC");

        //分页查询并转换
        IPage<StatTotalLearnDTO> page = baseService.paging(reqDTO);

        return super.success(page);
    }

    /**
     * 查找最近一周数据，用于控制台图表显示
     * @return
     */
    @ApiOperation(value = "查找最近一周数据")
    @PostMapping("/week")
    public ApiRest<List<StatTotalLearnDTO>> week() {

        // 开始时间
        StatTotalLearnReqDTO query = new StatTotalLearnReqDTO();
        this.fillDateQuery(query, -6);
        query.setOrderType("ASC");

        PagingReqDTO<StatTotalLearnReqDTO> reqDTO = new PagingReqDTO<>();
        reqDTO.setParams(query);
        reqDTO.setCurrent(1);
        reqDTO.setSize(7);

        IPage<StatTotalLearnDTO> page = baseService.paging(reqDTO);
        return super.success(page.getRecords());
    }


    /**
     * 填充本周时间
     * @param params
     */
    private void fillDateQuery(StatTotalLearnReqDTO params, int day){
        params.setEndDate(DateUtils.dateNow("yyyy-MM-dd"));
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(System.currentTimeMillis());
        cl.add(Calendar.DATE, day);
        params.setStartDate(DateUtils.formatDate(cl.getTime(), "yyyy-MM-dd"));
    }
}
